<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form 
      :model="queryParams" 
      ref="queryForm" 
      size="small" 
      :inline="true" 
      v-show="showSearch" 
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="taskName">
        <el-input 
          v-model="queryParams.taskName" 
          placeholder="请输入任务名称" 
          clearable 
          @keyup.enter.native="handleQuery" 
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 350px"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar 
        :showSearch.sync="showSearch" 
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 任务列表表格 -->
    <el-table 
      v-loading="loading" 
      :data="reportList" 
      border 
      stripe 
      highlight-current-row
      @row-dblclick="handleView"
    >
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="180" show-overflow-tooltip />
      <el-table-column label="任务类型" align="center" width="100">
        <template slot-scope="scope">
          <el-tag 
            :type="getTaskTypeTagType(scope.row.openUnit)" 
            size="small"
          >
            {{ getTaskTypeLabel(scope.row.openUnit) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" min-width="150" />
      <el-table-column label="结束时间" align="center" prop="endTime" min-width="150" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag 
            :type="getStatusTagType(scope.row.isOpen)" 
            size="small"
          >
            {{ getStatusLabel(scope.row.isOpen) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button 
            type="text" 
            icon="el-icon-view" 
            size="mini"
            @click="handleViewIcon(scope.row)"
          >
            查看详情
          </el-button>
          <el-button 
            type="text" 
            icon="el-icon-view" 
            size="mini"
            @click="handleViewLower(scope.row)"
          >
            查看下级
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination 
      v-show="total > 0" 
      :total="total" 
      :page.sync="queryParams.pageNum" 
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 测评结果抽屉 -->
    <el-drawer 
      :title="drawerTitle" 
      :visible.sync="resultDrawerVisible" 
      direction="rtl" 
      size="85%"
      :destroy-on-close="true" 
      class="result-drawer" 
      :before-close="handleDrawerClose"
    >
      <div class="drawer-container">
        <!-- 主要内容区域 -->
        <splitpanes :horizontal="false" class="default-theme" style="height: calc(100% - 120px)">
          <!-- 区域树面板 -->
          <pane :size="deptPaneSize" v-show="showDeptPane">
            <div class="dept-panel">
              <div class="panel-header">
                <h4><i class="el-icon-office-building"></i> 区域列表</h4>
              </div>
              <div class="panel-content">
                <el-table 
                  v-loading="deptLoading" 
                  :data="filteredDeptList" 
                  border 
                  stripe 
                  highlight-current-row
                  @row-click="handleDeptRowClick"
                  :row-class-name="getDeptRowClassName"
                  style="width: 100%"
                  size="mini"
                  row-key="deptId"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  empty-text="暂无区域数据"
                >
                  <el-table-column label="区域名称" prop="label" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <i :class="getDeptIcon(scope.row)"></i>
                      <span style="margin-left: 5px">{{ scope.row.deptName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" prop="type" width="60" align="center">
                    <template slot-scope="scope">
                      <el-badge :value="getDeptTypeName(scope.row.type)" type="primary" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="100">
                    <template slot-scope="scope">
                      <el-button type="text" icon="el-icon-view" size="mini" @click="handleView(scope.row)">查看报告</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </pane>
          
          <!-- 用户列表面板 -->
          <pane :size="userPaneSize">
            <div class="user-panel">
              <div class="panel-header">
                <h4><i class="el-icon-user"></i> {{ selectedDeptName ? `${selectedDeptName} - 用户列表` : '用户列表' }}</h4>
                <!-- 用户搜索表单 -->
                <el-form 
                  :model="resultQueryParams" 
                  ref="resultQueryForm" 
                  size="small" 
                  :inline="true"
                  v-show="showResultSearch" 
                  label-width="68px"
                  style="margin-top: 10px"
                >
                  <el-form-item label="用户名称" prop="userName">
                    <el-input 
                      v-model="resultQueryParams.userName" 
                      placeholder="请输入用户名称" 
                      clearable 
                      style="width: 180px"
                      @keyup.enter.native="handleResultQuery" 
                    />
                  </el-form-item>
                
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleResultQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetResultQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
              
              <div class="panel-content">
                <!-- 用户列表表格 -->
                <el-table 
                  v-loading="resultLoading" 
                  :data="userList" 
                  border 
                  stripe 
                  highlight-current-row
                  style="margin-top: 10px"
                  empty-text="暂无用户数据"
                  @sort-change="handleUserSortChange"
                >
                  <el-table-column type="index" label="序号" width="50" align="center" />
                  <el-table-column label="用户名称" align="center" prop="userName" min-width="100" show-overflow-tooltip sortable="custom" />
                  <el-table-column label="用户昵称" align="center" prop="nickName" min-width="100" show-overflow-tooltip />
                  <el-table-column label="区域" align="center" prop="dept.deptName" min-width="120" show-overflow-tooltip />
                  <el-table-column label="填写状态" align="center" width="100">
                    <template slot-scope="scope">
                      <el-tag :type="getTaskStatusType(scope.row.taskStatus)" size="small">
                        {{ getTaskStatusText(scope.row.taskStatus) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                      <el-button 
                        v-if="scope.row.taskStatus && scope.row.taskStatus != '0'" 
                        type="success" 
                        size="mini" 
                        icon="el-icon-document"
                        @click="viewUserReport(scope.row)"
                      >查看报告</el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 用户列表分页 -->
                <pagination 
                  v-show="resultTotal > 0" 
                  :total="resultTotal" 
                  :page.sync="resultQueryParams.pageNum" 
                  :limit.sync="resultQueryParams.pageSize" 
                  @pagination="getUserList"
                  style="margin-top: 10px"
                />
              </div>
            </div>
          </pane>
        </splitpanes>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listStudentReport } from '@/api/report/student'
import RightToolbar from '@/components/RightToolbar'
import Pagination from '@/components/Pagination'
// 新增：抽屉与数据所需依赖
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import { listUser, getUser } from '@/api/system/user'
import { listDept } from '@/api/system/dept'
import { listAssess } from '@/api/system/assess'

export default {
  name: 'StudentReport',
  components: { RightToolbar, Pagination, Splitpanes, Pane },
  data() {
    return {
      // 显示搜索
      showSearch: true,
      // 加载状态
      loading: true,
      // 总条数
      total: 0,
      // 报告列表
      reportList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        dateRange: null,
        startTime: null,
        endTime: null
      },

      // ===== 抽屉所需状态（与 old 页面一致） =====
      resultLoading: false,
      deptLoading: false,
      showResultSearch: true,
      showDeptPane: true,
      deptPaneSize: 25,
      userPaneSize: 75,

      resultDrawerVisible: false,
      currentTaskId: null,
      currentTaskName: '',
      taskInfo: {},

      // 区域相关
      deptOptions: [],
      filteredDeptList: [],
      selectedDeptId: null,
      selectedDeptName: null,
      deptQueryParams: {
        deptName: undefined
      },

      // 用户列表
      userList: [],
      resultTotal: 0,

      // 结果查询参数
      resultQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        deptId: undefined,
        taskId: undefined,
        taskStatus: undefined,
        createUser: undefined,
        orderByColumn: null,
        isAsc: null
      },

      // 缓存
      userCache: {},
      deptCache: {}
    }
  },
  computed: {
    drawerTitle() {
      return `测评结果 - ${this.currentTaskName || ''}`
    },
    isPersonalArea() {
      return this.taskInfo && this.taskInfo.createUser
    }
  },
  watch: {
    'deptQueryParams.deptName'(val) {
      this.filterDeptList()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleView(row){
      console.log(row)
      
      this.$router.push({ 
        path: '/reportAll', 
        query: { 
          deptId:row.deptId,
          taskId:this.currentTaskId,
          name:row.type
        }
      })
    },
    handleViewIcon(row){
        this.$router.push({ 
        path: '/reportAll', 
        query: { 
          deptId:row.createDept,
          taskId:row.id,
          name:row.openUnit
        }
      })
    },
    /** 查询报告列表 */
    getList() {
      this.loading = true
      // 处理日期范围
      if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        this.queryParams.startTime = this.queryParams.dateRange[0]
        this.queryParams.endTime = this.queryParams.dateRange[1]
      } else {
        this.queryParams.startTime = null
        this.queryParams.endTime = null
      }

      listStudentReport(this.queryParams).then(response => {
        this.reportList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.dateRange = null
      this.queryParams.startTime = null
      this.queryParams.endTime = null
      this.handleQuery()
    },
    /** 查看详情 */
    // handleView(row) {
    //   this.$router.push({ 
    //     path: '/report/student/detail', 
    //     query: { 
    //       taskId: row.id,
    //       taskName: row.taskName 
    //     }
    //   })
    // },

    // ===== 以下为“查看下级”抽屉逻辑，复用 old 页面的实现 =====

    /** 点击查看下级（打开抽屉） */
    async handleViewLower(row) {
      try {
        if (!row || !row.id) {
          this.$modal && this.$modal.msgError ? this.$modal.msgError('任务信息无效') : this.$message.error('任务信息无效')
          return
        }
        // 懒加载必要缓存
        await Promise.all([this.getAllUsers(), this.getAllDepts()])

        this.currentTaskId = row.id
        this.currentTaskName = row.taskName || '未知任务'
        this.taskInfo = row
        this.resultDrawerVisible = true

        this.resetResultQueryParams()
        this.resultQueryParams.taskId = row.id

        if (row.createUser) {
          await this.handleCreateUserMode(row)
        } else {
          await this.handleCreateDeptMode()
        }
      } catch (error) {
        console.error('查看下级失败:', error)
        this.$modal && this.$modal.msgError ? this.$modal.msgError('查看下级失败，请稍后重试') : this.$message.error('查看下级失败，请稍后重试')
      }
    },

    /** 处理 createUser 模式（个人模式） */
    async handleCreateUserMode(row) {
      await this.$nextTick()
      this.showDeptPane = false
      this.deptPaneSize = 0
      this.userPaneSize = 100
      this.resultQueryParams.createUser = row.createUser
      await this.getUserList()
    },

    /** 处理 createDept 模式（区域模式） */
    async handleCreateDeptMode() {
      this.showDeptPane = true
      this.deptPaneSize = 25
      this.userPaneSize = 75
      await this.getDeptTree()
      this.resetResultQuery()
    },

    /** 获取所有部门数据（缓存） */
    async getAllDepts() {
      try {
        const response = await listDept()
        if (response && response.data) {
          const deptMap = {}
          this.processDeptData(response.data, deptMap)
          this.deptCache = deptMap
        }
      } catch (e) {
        console.error('获取部门数据失败:', e)
      }
    },
    processDeptData(depts, deptMap) {
      if (!Array.isArray(depts)) return
      depts.forEach(dept => {
        if (dept && dept.deptId !== undefined) {
          deptMap[String(dept.deptId)] = dept
          if (Array.isArray(dept.children)) {
            this.processDeptData(dept.children, deptMap)
          }
        }
      })
    },

    /** 获取所有用户数据（缓存） */
    async getAllUsers() {
      try {
        const response = await listUser({ pageSize: 9999 })
        if (response && response.rows) {
          const userMap = {}
          response.rows.forEach(user => {
            if (user && user.userId !== undefined) {
              userMap[String(user.userId)] = user
            }
          })
          this.userCache = userMap
        }
      } catch (e) {
        console.error('获取用户数据失败:', e)
      }
    },

    /** 查询区域树并初始化选中 */
    async getDeptTree() {
      try {
        this.deptLoading = true
        const response = await listDept()
        if (!response || !response.data) {
          this.$modal && this.$modal.msgError ? this.$modal.msgError('获取区域数据失败') : this.$message.error('获取区域数据失败')
          return
        }
        this.deptOptions = this.handleTree(response.data, 'deptId')
        await this.initializeDeptSelection()
      } catch (error) {
        console.error('获取区域树数据失败:', error)
        this.$modal && this.$modal.msgError ? this.$modal.msgError('获取区域数据失败，请稍后重试') : this.$message.error('获取区域数据失败，请稍后重试')
      } finally {
        this.deptLoading = false
      }
    },

    /** 初始化区域选择 */
    async initializeDeptSelection() {
      await this.$nextTick()
      this.filterDeptList(true)
      if (this.filteredDeptList && this.filteredDeptList.length > 0) {
        const firstNode = this.getFirstParentNode(this.filteredDeptList)
        if (firstNode && firstNode.deptId) {
          this.selectedDeptId = firstNode.deptId
          this.selectedDeptName = firstNode.deptName
          this.resultQueryParams.deptId = firstNode.deptId
          this.filterDeptList()
          await this.getUserList()
        } else {
          this.$modal && this.$modal.msgWarning ? this.$modal.msgWarning('未找到可用的区域节点') : this.$message.warning('未找到可用的区域节点')
        }
      } else {
        this.$modal && this.$modal.msgWarning ? this.$modal.msgWarning('没有可显示的区域数据') : this.$message.warning('没有可显示的区域数据')
      }
    },

    /** 树过滤：按 createDept 限制 */
    getFilteredDeptsByCreateDept(depts) {
      if (!this.taskInfo || !this.taskInfo.createDept) return depts
      let ids = []
      const createDept = this.taskInfo.createDept
      if (Array.isArray(createDept)) ids = createDept.map(id => id.toString())
      else if (typeof createDept === 'string' && createDept.includes(',')) ids = createDept.split(',').map(id => id.trim())
      else if (createDept) ids = [createDept.toString()]
      return this.filterDeptTreeByCreateDeptIds(depts, ids)
    },
    filterDeptTreeByCreateDeptIds(depts, createDeptIds) {
      if (!depts || !createDeptIds || !createDeptIds.length) return []
      const findCreateDept = (deptList) => {
        for (const dept of deptList) {
          if (!dept || dept.deptId === undefined || dept.deptId === null) continue
          const deptId = dept.deptId.toString()
          if (createDeptIds.includes(deptId)) {
            return this.deepCloneDept(dept)
          }
          if (dept.children && dept.children.length) {
            const found = findCreateDept(dept.children)
            if (found) return found
          }
        }
        return null
      }
      const result = findCreateDept(depts)
      return result ? [result] : []
    },

    /** 根据选中部门仅显示该节点及子节点 */
    filterDeptTreeBySelectedId(depts, selectedId) {
      if (!depts || !selectedId) return depts
      const findTargetDept = (deptList) => {
        for (const dept of deptList) {
          if (!dept || dept.deptId === undefined || dept.deptId === null) continue
          const deptId = dept.deptId.toString()
          if (deptId === selectedId.toString()) {
            return [{ ...dept }]
          }
          if (dept.children && dept.children.length) {
            const found = findTargetDept(dept.children)
            if (found.length > 0) return found
          }
        }
        return []
      }
      return findTargetDept(depts)
    },

    /** 深拷贝部门对象 */
    deepCloneDept(dept) {
      if (!dept) return null
      try { return JSON.parse(JSON.stringify(dept)) } catch { return { ...dept } }
    },

    /** 过滤区域列表（名称/范围/选中） */
    filterDeptList(skipSelectedFilter = false) {
      if (!this.deptOptions) {
        this.filteredDeptList = []
        return
      }
      this.deptLoading = true
      let baseData = this.deptOptions
      if (this.currentTaskId && this.taskInfo && this.taskInfo.createDept) {
        baseData = this.getFilteredDeptsByCreateDept(this.deptOptions)
      }
      if (this.selectedDeptId && !skipSelectedFilter && !(this.currentTaskId && this.taskInfo && this.taskInfo.createDept)) {
        baseData = this.filterDeptTreeBySelectedId(baseData, this.selectedDeptId)
      }
      if (this.deptQueryParams.deptName) {
        this.filteredDeptList = this.filterTreeByName(baseData, this.deptQueryParams.deptName)
      } else {
        this.filteredDeptList = baseData
      }
      this.deptLoading = false
    },

    /** 获取第一个父节点（初始化用） */
    getFirstParentNode(tree) {
      if (!Array.isArray(tree) || tree.length === 0) return null
      const findFirst = (nodes) => {
        for (const n of nodes) {
          if (!n) continue
          if (!n.parentId || n.parentId === 0) return n
          if (n.children && n.children.length) {
            const res = findFirst(n.children)
            if (res) return res
          }
        }
        return nodes[0]
      }
      return findFirst(tree)
    },

    /** 区域表格行点击 */
    handleDeptRowClick(row) {
      if (!row || !row.deptId) return
      this.selectedDeptId = row.deptId
      this.selectedDeptName = row.deptName
      this.resultQueryParams.deptId = row.deptId
      this.filterDeptList()
      this.getUserList()
    },
    getDeptRowClassName({ row }) {
      return row && this.selectedDeptId && String(row.deptId) === String(this.selectedDeptId) ? 'current-row' : ''
    },
    getDeptIcon(dept) {
      // 可根据 dept.type 定制，这里简化统一使用
      return 'el-icon-office-building'
    },

    /** 根据 createUser/部门 获取用户列表 */
    async getUserList() {
      try {
        this.resultLoading = true
        if (this.resultQueryParams.createUser) {
          await this.getUserListByCreateUser()
        } else {
          await this.getUserListByDept()
        }
      } finally {
        this.resultLoading = false
      }
    },
    async getUserListByCreateUser() {
      const userIds = this.parseUserIds(this.resultQueryParams.createUser)
      if (!userIds || userIds.length === 0) {
        this.userList = []
        this.resultTotal = 0
        return
      }
      const userPromises = userIds.map(userId => getUser(userId).catch(() => null))
      const responses = await Promise.all(userPromises)
      const allUsers = responses.filter(res => res && res.data).map(res => res.data)
      if (allUsers.length === 0) {
        this.userList = []
        this.resultTotal = 0
        return
      }
      const { pageNum = 1, pageSize = 10 } = this.resultQueryParams
      const startIndex = (pageNum - 1) * pageSize
      const endIndex = startIndex + pageSize
      const pagedUsers = allUsers.slice(startIndex, endIndex)
      await this.enrichUsersWithTaskStatus(pagedUsers)
      this.userList = pagedUsers
      this.resultTotal = allUsers.length
    },
    async getUserListByDept() {
      const params = this.buildUserQueryParams()
      const response = await listUser(params)
      this.userList = (response && response.rows) || []
      this.resultTotal = (response && response.total) || 0
    },
    buildUserQueryParams() {
      return {
        pageNum: this.resultQueryParams.pageNum || 1,
        pageSize: this.resultQueryParams.pageSize || 10,
        deptId: this.resultQueryParams.deptId,
        taskId: this.currentTaskId,
        userName: this.resultQueryParams.userName || undefined,
        phonenumber: this.resultQueryParams.phonenumber || undefined,
        taskStatus: this.resultQueryParams.taskStatus || undefined,
        orderByColumn: this.resultQueryParams.orderByColumn,
        isAsc: this.resultQueryParams.isAsc
      }
    },
    async enrichUsersWithTaskStatus(users) {
      if (!users || users.length === 0) return
      try {
        const assessParams = { taskId: this.currentTaskId, userIds: users.map(u => u.userId).join(',') }
        const assessResponse = await listAssess(assessParams)
        const taskStatusMap = new Map()
        if (assessResponse && assessResponse.rows) {
          assessResponse.rows.forEach(item => {
            if (item.userId && item.taskStatus !== undefined) {
              taskStatusMap.set(item.userId, item.taskStatus)
            }
          })
        }
        users.forEach(u => { u.taskStatus = taskStatusMap.get(u.userId) || 0 })
      } catch (e) {
        console.error('获取用户任务状态失败:', e)
        users.forEach(u => { u.taskStatus = 0 })
      }
    },
    parseUserIds(createUser) {
      if (!createUser) return []
      try {
        if (typeof createUser === 'string') {
          return createUser.split(',').map(id => id.trim()).filter(Boolean)
        } else if (Array.isArray(createUser)) {
          return createUser.map(id => String(id).trim()).filter(Boolean)
        } else {
          return [String(createUser).trim()]
        }
      } catch {
        return []
      }
    },

    /** 用户列表排序变化处理 */
    handleUserSortChange({ prop, order }) {
      this.resultQueryParams.orderByColumn = prop
      this.resultQueryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
      this.getUserList()
    },
    /** 搜索结果按钮操作 */
    handleResultQuery() {
      this.resultQueryParams.pageNum = 1
      this.getUserList()
    },
    /** 重置结果查询 */
    resetResultQuery() {
      this.resultQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        deptId: this.resultQueryParams.deptId,
        taskId: this.currentTaskId,
        taskStatus: undefined,
        createUser: this.resultQueryParams.createUser,
        orderByColumn: null,
        isAsc: null
      }
      this.getUserList()
    },

    /** 抽屉关闭 */
    async handleDrawerClose() {
      try {
        this.resultDrawerVisible = false
        this.currentTaskId = null
        this.currentTaskName = ''
        this.taskInfo = {}
        this.selectedDeptId = null
        this.resetResultQueryParams()
        this.userList = []
        this.resultTotal = 0
        this.deptOptions = []
        this.filteredDeptList = []
        this.showDeptPane = true
        this.deptPaneSize = 25
        this.userPaneSize = 75
        await this.getList()
      } catch (e) {
        console.error('关闭抽屉时发生错误:', e)
        this.resultDrawerVisible = false
      }
    },
    resetResultQueryParams() {
      this.resultQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        deptId: undefined,
        taskId: undefined,
        taskStatus: undefined,
        createUser: undefined,
        orderByColumn: null,
        isAsc: null
      }
    },

    // 工具方法
    getUserNicknameById(userId) {
      if (!userId) return ''
      if (typeof userId === 'string' && userId.includes(',')) {
        const ids = userId.split(',').map(id => id.trim())
        return ids.map(id => this.userCache[id]?.userName || this.userCache[id]?.nickName || id).join(', ')
      }
      const id = String(userId)
      const user = this.userCache[id]
      return user ? (user.userName || user.nickName || id) : id
    },
    getDeptNameById(deptId) {
      if (!deptId) return ''
      if (typeof deptId === 'string' && deptId.includes(',')) {
        const ids = deptId.split(',').map(id => id.trim())
        return ids.map(id => this.deptCache[id]?.deptName || id).join(', ')
      }
      const id = String(deptId)
      const dept = this.deptCache[id]
      return dept ? (dept.deptName || id) : id
    },
    getOpenTargets(openTarget) {
      if (!openTarget) return []
      try {
        const targets = JSON.parse(openTarget)
        return Array.isArray(targets) ? targets : [targets]
      } catch {
        return [openTarget]
      }
    },
    getAreaTypeName(type) {
      const numType = type ? parseInt(type, 10) : 0
      const typeMap = { 1:'市级',2:'区县',3:'教育局',4:'学校',5:'年级',6:'班级',7:'个人' }
      return typeMap[numType] || '未知'
    },
    getDeptTypeName(type){
      const options = [
        { dictLabel: '市级', dictValue: '1' },
        { dictLabel: '区县', dictValue: '2' },
        { dictLabel: '教育局', dictValue: '3' },
        { dictLabel: '学校', dictValue: '4' },
        { dictLabel: '年级', dictValue: '5' },
        { dictLabel: '班级', dictValue: '6' },
        { dictLabel: '个人', dictValue: '7' }
      ]
      const item = options.find(i => i.dictValue == type)
      return item?.dictLabel || '机构'
    },
    getTaskStatusType(taskStatus) {
      return taskStatus && taskStatus != '0' ? 'success' : 'info'
    },
    getTaskStatusText(taskStatus) {
      return taskStatus && taskStatus != '0' ? '已填写' : '未填写'
    },
    
    /** 获取任务类型标签类型（与原实现一致） */
    getTaskTypeTagType(openUnit) {
      const colorMap = {
        1: 'danger',
        2: 'warning',
        3: 'info',
        4: 'primary',
        5: 'success',
        6: 'success',
        7: 'danger'
      };
      const key = Number(openUnit);
      return colorMap[key] || '';
    },
    
    /** 获取任务类型标签文本（与原实现一致） */
    getTaskTypeLabel(openUnit) {
      const typeMap = {
        1: '市级',
        2: '区县',
        3: '教育局',
        4: '学校',
        5: '年级',
        6: '班级',
        7: '个人'
      };
      const key = Number(openUnit);
      return typeMap[key] || '未知';
    },
    viewUserReport(row){

       window.open(
        `/detail?userId=${row.userId}&taskId=${this.currentTaskId}`,
        "_blank"
      );
    },
    /** 获取状态标签类型（与原实现一致） */
    getStatusTagType(isOpen) {
      return String(isOpen) === '1' ? 'success' : 'warning';
    },
    
    /** 获取状态标签文本（与原实现一致） */
    getStatusLabel(isOpen) {
      return String(isOpen) === '1' ? '进行中' : '已结束';
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

/* 抽屉样式 */
.result-drawer {
  padding: 0;
}

.result-drawer ::v-deep .el-drawer__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  margin-bottom: 0;
  border-bottom: 1px solid #e6e6e6;
}

.result-drawer ::v-deep .el-drawer__title {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.result-drawer ::v-deep .el-drawer__close-btn {
  color: white;
  font-size: 20px;
}

.result-drawer ::v-deep .el-drawer__close-btn:hover {
  color: #f0f0f0;
}

.drawer-container {
  height: calc(100vh - 60px);
  overflow: hidden;
  padding: 0;
  background-color: #f8f9fa;
}

/* 面板样式 */
.dept-panel, .user-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  margin: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-header {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
  flex-shrink: 0;
}

.panel-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.panel-header h4 i {
  margin-right: 8px;
  color: #667eea;
}

.panel-content {
  flex: 1;
  overflow: auto;
  padding: 15px;
}

/* 表格样式优化 */
.panel-content ::v-deep .el-table {
  border-radius: 6px;
  overflow: hidden;
}

.panel-content ::v-deep .el-table th {
  background-color: #fafbfc;
  color: #2c3e50;
  font-weight: 600;
  border-bottom: 2px solid #e6e6e6;
}

.panel-content ::v-deep .el-table td {
  border-bottom: 1px solid #f0f0f0;
}

.panel-content ::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafbfc;
}

.panel-content ::v-deep .el-table__row:hover td {
  background-color: #e8f4fd !important;
}

/* 搜索表单样式 */
.panel-header .el-form {
  background: white;
  padding: 15px;
  border-radius: 6px;
  margin-top: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 按钮样式优化 */
.panel-content ::v-deep .el-button--mini {
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
}

.panel-content ::v-deep .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.panel-content ::v-deep .el-button--success {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
  border: none;
}

/* 标签样式优化 */
.panel-content ::v-deep .el-tag {
  border-radius: 12px;
  padding: 0 8px;
  font-size: 12px;
}

.panel-content ::v-deep .el-tag--success {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
  border: none;
  color: white;
}

.panel-content ::v-deep .el-tag--info {
  background: linear-gradient(135deg, #bdc3c7 0%, #2c3e50 100%);
  border: none;
  color: white;
}

/* 分页样式 */
.panel-content ::v-deep .el-pagination {
  text-align: center;
  padding: 15px 0;
}

/* 分割面板样式 */
::v-deep .splitpanes__pane {
  background: transparent;
}

::v-deep .splitpanes__splitter {
  background: #e6e6e6;
  position: relative;
}

::v-deep .splitpanes__splitter:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  height: 30px;
  background: #667eea;
  border-radius: 3px;
  opacity: 0;
  transition: opacity 0.3s;
}

::v-deep .splitpanes__splitter:hover:before {
  opacity: 0.3;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .drawer-container {
    padding: 5px;
  }
  
  .dept-panel, .user-panel {
    margin: 5px;
  }
  
  .panel-header {
    padding: 10px 15px;
  }
  
  .panel-content {
    padding: 10px;
  }
}
</style>
